// $Id: wfits.c 83 2012-07-23 17:17:59Z alan.watson.f $

#include <stdio.h>
#include <string.h>
#include <time.h>

#include <sys/time.h>

#include "wfits.h"

void
oaxaca_wfits_write_basic_header(FILE *fp, size_t nx, size_t ny)
{
  oaxaca_wfits_write_boolean(fp, "SIMPLE", 1);
  oaxaca_wfits_write_long   (fp, "BITPIX", 16);
  oaxaca_wfits_write_long   (fp, "NAXIS" , 2);
  oaxaca_wfits_write_long   (fp, "NAXIS1", (long) nx);
  oaxaca_wfits_write_long   (fp, "NAXIS2", (long) ny);
}

void
oaxaca_wfits_write_boolean(FILE *fp, const char *name, int value)
{
  char s[81];
  sprintf(s, "%20.20s", value ? "T" : "F");
  fprintf(fp, "%-8.8s= %-70.70s", name, s);
}

void
oaxaca_wfits_write_long(FILE *fp, const char *name, long value)
{
  char s[81];
  sprintf(s, "%20ld", value);
  fprintf(fp, "%-8.8s= %-70.70s", name, s);
}

void
oaxaca_wfits_write_double(FILE *fp, const char *name, double value, const char *format)
{
  char s[81];
  sprintf(s, format, value);
  fprintf(fp, "%-8.8s= %-70.70s", name, s);
}

void
oaxaca_wfits_write_string(FILE *fp, const char *name, const char *value)
{
  char s[81];
  sprintf(s, "'%s'", value);
  fprintf(fp, "%-8.8s= %-70.70s", name, s);
}

void oaxaca_wfits_write_date(FILE *fp, const char *name)
{
  static char s[] = "YYYY-DD-MMTHH:MM:SS";
  static char t[] = "'YYYY-DD-MMTHH:MM:SS.SSS'";
  struct timeval tv;
  gettimeofday(&tv, NULL);
  struct tm *tm = localtime(&tv.tv_sec);
  strftime(s, sizeof(s), "%FT%T", tm);
  sprintf(t, "'%s.%03lu'", s, (unsigned long) (tv.tv_usec / 1000));
  fprintf(fp, "%-8.8s= %-70.70s", name, t);
}

void
oaxaca_wfits_write_data(FILE *fp, array_short_t *data)
{
  fprintf(fp, "%-80.80s", "END");
  
  {
    size_t n = ftell(fp) % 2880;
    if (n > 0) {
      char fill[2880 - n];
      memset(fill, ' ', sizeof(fill));
      fwrite(fill, sizeof(fill), 1, fp);
    }
  }
  
  for (size_t iy = 0; iy < data->ny; ++iy) {
    unsigned short buf[data->nx];
    for (size_t ix = 0; ix < data->nx; ++ix) {
      unsigned short us = * (unsigned short *) &data->z[iy][ix];
      buf[ix] = (us << 8) | (us >> 8);
    }
    fwrite(buf, sizeof(buf), 1, fp);
  }

  {
    size_t n = ftell(fp) % 2880;
    if (n > 0) {
      char fill[2880 - n];
      memset(fill, 0, sizeof(fill));
      fwrite(fill, sizeof(fill), 1, fp);
    }
  }
}
